package com.nyp.lotteryf.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.ejb.DuplicateKeyException;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.event.AjaxBehaviorEvent;
import javax.inject.Named;

import com.nyp.lotteryf.entity.User;

@Named
@ApplicationScoped
public class NameCollectionAppBean {
	
	private List<User> users = new ArrayList<User>();
	private List<User> winners = new ArrayList<User>();
	
	public void addUser(User user) throws DuplicateKeyException{
		if(users.contains(user)){
			throw new DuplicateKeyException();
		}
		users.add(user);
	}
	
	public List<User> selectRandomAddresses(int num) throws IndexOutOfBoundsException{
		if(num > users.size()){
			throw new IndexOutOfBoundsException();
		}
		List<User> copy = new ArrayList<User>(users);
		List<User> ret = new ArrayList<User>();
		Random rand = new Random(System.currentTimeMillis());
		for(int i=0; i<num; i++){
			int index = rand.nextInt(copy.size());
			ret.add(copy.remove(index));
		}
		return ret;		
	}

	public List<User> getUsers() {
		return users;
	}
	
	public void startLottery(AjaxBehaviorEvent event){
		winners = selectRandomAddresses(2);
	}

	public List<User> getWinners() {
		return winners;
	}

}
